package com.shop.servlet;

import com.shop.service.IOrderService;
import com.shop.service.OrderService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/RechargeServlet")
public class RechargeServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try{
            // 获取参数
            String amountStr = req.getParameter("selectedAmount");
            String studentId = req.getParameter("studentId");
            double studentMoney = Double.parseDouble(req.getParameter("studentMoney"));
            String paymentMethod = req.getParameter("paymentMethod");

            System.out.println("RechargeServlet:24: " + studentId + " "+studentMoney+ " " + amountStr + " " + paymentMethod);
            // 验证参数
            if (amountStr == null || amountStr.isEmpty()) {
                throw new Exception("请选择充值金额");
            }

            double amount = Double.parseDouble(amountStr);
            System.out.println("RechargeServlet:31: " + amount);
            if (amount <= 0) {
                throw new Exception("充值金额必须大于0");
            }

            if (!"alipay".equals(paymentMethod) && !"wechat".equals(paymentMethod)) {
                throw new Exception("请选择有效的支付方式");
            }

            // 执行充值操作
            IOrderService iorderService = new OrderService();
            double money = studentMoney + amount;
            System.out.println("RechargeServlet:43: " + money);
            boolean recharge = iorderService.updateMoney1(studentId, money);

            if( recharge){
                // 重定向到充值成功页面
                req.setAttribute("amount", amount);
                req.setAttribute("studentId", studentId);
                req.setAttribute("paymentMethod", paymentMethod);
                req.getRequestDispatcher("recharge_success.jsp").forward(req, resp);
            }else{
                resp.sendRedirect("recharge.jsp");
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
